package com.english.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.english.entity.ClassHoursLog;
import com.english.entity.StudentClassHours;
import com.english.mapper.StudentClassHoursMapper;
import com.english.mapper.ClassHoursLogMapper;
import com.english.service.StudentClassHoursService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

/**
 * 学生班级课时服务实现
 *
 * @author wlq
 * @since 2025-08-06
 */
@Slf4j
@Service
public class StudentClassHoursServiceImpl extends ServiceImpl<StudentClassHoursMapper, StudentClassHours>
        implements StudentClassHoursService {

    @Autowired
    private ClassHoursLogMapper classHoursLogMapper;

    @Override
    public List<StudentClassHours> getStudentClassHours(Long studentId) {
        return baseMapper.selectByStudentIdWithDetails(studentId);
    }

    @Override
    public List<StudentClassHours> getClassStudentHours(Long classId) {
        return baseMapper.selectByClassIdWithDetails(classId);
    }

    @Override
    public StudentClassHours getStudentClassHours(Long studentId, Long classId) {
        return baseMapper.selectByStudentAndClass(studentId, classId);
    }

    @Override
    public Integer getTotalRemainingHours(Long studentId) {
        Integer total = baseMapper.selectTotalRemainingHours(studentId);
        return total != null ? total : 0;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean adjustStudentClassHours(Long studentId, Long classId, Integer changeValue,
                                          ClassHoursLog.ChangeType changeType, String title,
                                          String description, Long adminId) {
        try {
            // 获取当前课时信息
            StudentClassHours currentHours = getStudentClassHours(studentId, classId);
            if (currentHours == null) {
                // 如果不存在，先初始化
                initStudentClassHours(studentId, classId);
                currentHours = getStudentClassHours(studentId, classId);
            }

            int beforeHours = currentHours.getRemainingHours();
            int afterHours = beforeHours + changeValue;

            // 确保课时不会变成负数
            if (afterHours < 0) {
                log.warn("课时调整失败：剩余课时不足。当前：{}，变动：{}", beforeHours, changeValue);
                return false;
            }

            // 更新课时
            if (changeValue > 0) {
                // 增加课时
                currentHours.setTotalHours(currentHours.getTotalHours() + changeValue);
            } else {
                // 减少课时
                currentHours.setUsedHours(currentHours.getUsedHours() + Math.abs(changeValue));
            }
            currentHours.setRemainingHours(afterHours);

            boolean updateResult = updateById(currentHours);
            if (!updateResult) {
                return false;
            }

            // 记录日志
            ClassHoursLog log = new ClassHoursLog();
            log.setStudentId(studentId);
            log.setClassId(classId);
            log.setChangeValue(changeValue);
            log.setChangeType(changeType);
            log.setTitle(title);
            log.setDescription(description);
            log.setBeforeHours(beforeHours);
            log.setAfterHours(afterHours);
            log.setAdminId(adminId);

            classHoursLogMapper.insert(log);
            return true;

        } catch (Exception e) {
            log.error("调整课时失败：{}", e.getMessage(), e);
            throw e;
        }
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean consumeHoursOnSignOut(Long studentId, Long classId, Long adminId, Long attendanceId) {
        try {
            // 获取当前课时信息
            StudentClassHours currentHours = getStudentClassHours(studentId, classId);
            if (currentHours == null || currentHours.getRemainingHours() <= 0) {
                log.warn("签退扣减失败：学生课时不足。学生ID：{}，班级ID：{}", studentId, classId);
                return false;
            }

            int beforeHours = currentHours.getRemainingHours();
            int afterHours = beforeHours - 1;

            // 更新课时
            currentHours.setUsedHours(currentHours.getUsedHours() + 1);
            currentHours.setRemainingHours(afterHours);

            boolean updateResult = updateById(currentHours);
            if (!updateResult) {
                return false;
            }

            // 记录日志
            ClassHoursLog hoursLog = new ClassHoursLog();
            hoursLog.setStudentId(studentId);
            hoursLog.setClassId(classId);
            hoursLog.setChangeValue(-1);
            hoursLog.setChangeType(ClassHoursLog.ChangeType.SIGN_OUT);
            hoursLog.setTitle("签退扣减课时");
            hoursLog.setDescription("学生签退自动扣减1课时");
            hoursLog.setBeforeHours(beforeHours);
            hoursLog.setAfterHours(afterHours);
            hoursLog.setAdminId(adminId);
            hoursLog.setAttendanceId(attendanceId);

            classHoursLogMapper.insert(hoursLog);
            return true;

        } catch (Exception e) {
            log.error("签退扣减课时失败：{}", e.getMessage(), e);
            throw e;
        }
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean addHoursOnRecharge(Long studentId, Long classId, Integer hours, Long rechargeId) {
        return adjustStudentClassHours(studentId, classId, hours,
                ClassHoursLog.ChangeType.RECHARGE, "充值增加课时",
                "充值增加" + hours + "课时", null);
    }

    @Override
    public boolean initStudentClassHours(Long studentId, Long classId) {
        try {
            // 检查是否已存在
            StudentClassHours existing = getStudentClassHours(studentId, classId);
            if (existing != null) {
                return true;
            }

            // 创建新记录
            StudentClassHours newRecord = new StudentClassHours();
            newRecord.setStudentId(studentId);
            newRecord.setClassId(classId);
            newRecord.setTotalHours(0);
            newRecord.setUsedHours(0);
            newRecord.setRemainingHours(0);

            return save(newRecord);

        } catch (Exception e) {
            log.error("初始化学生班级课时失败：{}", e.getMessage(), e);
            return false;
        }
    }

    @Override
    public List<ClassHoursLog> getHoursChangeLog(Long studentId, Long classId) {
        QueryWrapper<ClassHoursLog> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("student_id", studentId);
        if (classId != null) {
            queryWrapper.eq("class_id", classId);
        }
        queryWrapper.orderByDesc("create_time");
        return classHoursLogMapper.selectList(queryWrapper);
    }
} 